const { Sequelize } = require('sequelize');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// 根据环境选择配置
const env = process.env.NODE_ENV || 'development';

// 数据库配置
const config = {
  development: {
    host: process.env.DB_HOST || 'localhost',
    username: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || 'root',
    database: process.env.DB_NAME || 'blog_dev',
    dialect: 'mysql',
    port: process.env.DB_PORT || 3306,
    pool: {
      max: 10,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
    logging: console.log,
    define: {
      underscored: true, // 使用下划线命名
      underscoredAll: true // 所有表和字段都使用下划线命名
    }
  },
  test: {
    host: process.env.TEST_DB_HOST || 'localhost',
    username: process.env.TEST_DB_USER || 'root',
    password: process.env.TEST_DB_PASSWORD || 'root',
    database: process.env.TEST_DB_NAME || 'blog_test',
    dialect: 'mysql',
    port: process.env.TEST_DB_PORT || 3306,
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
    logging: false,
    define: {
      underscored: true,
      underscoredAll: true
    }
  },
  production: {
    host: process.env.PROD_DB_HOST,
    username: process.env.PROD_DB_USER,
    password: process.env.PROD_DB_PASSWORD,
    database: process.env.PROD_DB_NAME,
    dialect: 'mysql',
    port: process.env.PROD_DB_PORT || 3306,
    pool: {
      max: 20,
      min: 5,
      acquire: 30000,
      idle: 10000
    },
    logging: false,
    define: {
      underscored: true,
      underscoredAll: true
    }
  }
};

// 创建Sequelize实例
const sequelize = new Sequelize(
  config[env].database,
  config[env].username,
  config[env].password,
  config[env]
);

module.exports = {
  sequelize,
  Sequelize,
  config: config[env]
};